package com.v1.video.fragment;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.ListView;
import android.widget.Toast;

import com.iss.view.common.ToastAlone;
import com.iss.view.pulltorefresh.PullToRefreshBase;
import com.iss.view.pulltorefresh.PullToRefreshBase.Mode;
import com.iss.view.pulltorefresh.PullToRefreshBase.OnRefreshListener2;
import com.iss.view.pulltorefresh.PullToRefreshListView;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.umeng.analytics.MobclickAgent;
import com.v1.video.Constant;
import com.v1.video.R;
import com.v1.video.activity.MyLoginVideoActivity;
import com.v1.video.adapter.MyLoginVideoAdapter;
import com.v1.video.domain.LoginInfo;
import com.v1.video.domain.MyloginVideoEntity;
import com.v1.video.domain.VideoInfo4;
import com.v1.video.httpApi.V1VideoHttpApi;
import com.v1.video.httpmanager.RequestManager;
import com.v1.video.httpmanager.RequestManager.OnResponseListener;
import com.v1.video.util.Helper;
import com.v1.video.util.Logger;

import java.util.ArrayList;
import java.util.List;

/**
 * 视频显示
 * 
 * @author fengtao
 * 
 */
public class MyLoginVideoFragment extends V1BaseFragment {
	private final String TAG = "MyLoginVideoFragment";
	private PullToRefreshListView mRefreshListView;	
	private ListView mListView;
	private MyLoginVideoAdapter mAdapter;
	private int mPageIndex = 1;
	private List<VideoInfo4> mLstData = new ArrayList<VideoInfo4>();
	private LayoutInflater mInflater;
	private View mView,mEmptyView;
	private int mCurIndex = 0;
	private Handler handlerConverse;
	public int flag = 0;
	/**视频总条数*/
	private int totalListNum = 0;
	/**当前页数*/
	private int curIndex = 0;
	/**总页数*/
	private int page_num = 0;
	/**获取视频的条数*/
	private final int COUNT_GET_INFO = 10;
	/**不能上拉加载*/
	private boolean isNoUpDown = false;
	private boolean isDelete = false;
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		// TODO Auto-generated method stub
//		if (mView == null) {
			mInflater = inflater;
			mView = inflater
					.inflate(R.layout.fragment_my_login_video, container, false);
			initView();
			initData();
			setListener();
//		}
		return mView;
	}
	
	public MyLoginVideoFragment(Handler handlerConverse,int flag){
		this.handlerConverse= handlerConverse; 
		this.flag = flag;
	}

	private void initView() {
		mEmptyView = mInflater.inflate(R.layout.fragment_no_content, null);
		mRefreshListView = (PullToRefreshListView) mView
				.findViewById(R.id.lv_listView);
		mListView = mRefreshListView.getRefreshableView();
//		mRefreshListView.setScrollingWhileRefreshingEnabled(false);
		mRefreshListView.setMode(Mode.BOTH);
	}

	private void initData() {
//		clickStatistics(Constant.HOME_CLASSIFICATION_ID, "首页频道-" + mCid);
		mAdapter = new MyLoginVideoAdapter(getActivity(),handlerConverse,flag);
//		mAdapter.setmType(mType);
		mRefreshListView.setMode(Mode.BOTH);
		mListView.setAdapter(mAdapter);
//		if (mRefreshListView != null) {
//			mRefreshListView.doPullRefreshing(100);
//		}
//		for(int i = 0; i < 20;i++){
//			VideoInfo4 video = new VideoInfo4();
//			video.setImgUrl("http://img.mms.v1.cn/static/mms/images//201604111701509770.jpg");
//			video.setAt("1");
//			video.setTitle("测试标题"+i+"有的没的");
//			mLstData.add(video);
//		}
//		mAdapter.setLstData(mLstData);
		getServerData();
	}
	
	private void setListener() {
		mEmptyView.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				if (mRefreshListView != null) {
					mRefreshListView.doPullRefreshing(100);
				}
			}
		});
		mRefreshListView.setOnRefreshListener(new OnRefreshListener2() {

			@Override
			public void onPullDownToRefresh(PullToRefreshBase refreshView) {
				// TODO Auto-generated method stub
				mCurIndex = 0;
				Logger.i(TAG, "下拉刷新");
				curIndex = 0;
				if (Helper.checkConnection(getActivity())) {
					getServerData();
				}else{
					Message msg = handler.obtainMessage();
					msg.what = 0;
					handler.sendMessage(msg);
				}
			}

			@Override
			public void onPullUpToRefresh(PullToRefreshBase refreshView) {
				// TODO Auto-generated method stub
				Logger.i(TAG, "上拉加载");
				curIndex++;
				if (Helper.checkConnection(getActivity())) {
					getServerData();
				}else{
					Message msg = handler.obtainMessage();
					msg.what = 0;
					handler.sendMessage(msg);
				}
				
			}
		});
		mListView.setOnScrollListener(new OnScrollListener() {

			@Override
			public void onScrollStateChanged(AbsListView view, int scrollState) {
				// TODO Auto-generated method stub
				switch (scrollState) {
				case OnScrollListener.SCROLL_STATE_IDLE:
					ImageLoader.getInstance().resume();
					break;
				case OnScrollListener.SCROLL_STATE_TOUCH_SCROLL:
					ImageLoader.getInstance().pause();
					break;
				case OnScrollListener.SCROLL_STATE_FLING:
					ImageLoader.getInstance().pause();
					break;
				}
			}

			@Override
			public void onScroll(AbsListView view, int firstVisibleItem,
					int visibleItemCount, int totalItemCount) {
				// TODO Auto-generated method stub

			}
		});
	}
	
	public void setIsDeleteShow(boolean isDelete){
		this.isDelete = isDelete;
		if(mAdapter != null){
			mAdapter.isShowDelete(isDelete);
		}
		if(isDelete){
			if(isNoUpDown){
				if(mRefreshListView != null){
					mRefreshListView.setMode(Mode.DISABLED);
				}
			}else{
				if(mRefreshListView != null){
					Logger.i(TAG, "mRefreshListView.setMode(Mode.PULL_UP_TO_REFRESH)执行1111111111111111");
					mRefreshListView.setMode(Mode.PULL_FROM_END);
				}
			}
		}else{
			if(isNoUpDown){
				if(mRefreshListView != null){
					mRefreshListView.setMode(Mode.PULL_FROM_START);
				}
			}else{
				if(mRefreshListView != null){
					Logger.i(TAG, "mRefreshListView.setMode(Mode.PULL_UP_TO_REFRESH)执行222222222222222");
					mRefreshListView.setMode(Mode.BOTH);
				}
			}
		}
	}
	
	private void getServerData(){
		if(flag == MyLoginVideoActivity.FLAG_VIDEO){//获取视频数据
			getVideoList();
		}else{//获取收藏数据
			getVideoCollectList();
		}
	}
	
	/***
     * 获取收藏视频列表
     */
    private void getVideoCollectList(){
    	String url = V1VideoHttpApi.GET_COLLECT_VIDEO_LIST_USER() + "&uid="+LoginInfo.getInstance().getUserId()
				+"&p="+curIndex+"&s="+COUNT_GET_INFO+"&devid="+Constant.DEVICEID;
    	Logger.i(TAG, "收藏视频列表Url ="+url);
		RequestManager.getInstance().getRequest(getActivity(), url, null, MyloginVideoEntity.class, 0, "MyLoginVideoFragment", new OnResponseListener(){

			@Override
			public void onSuccess(Object object, int code, String message,String key) {
				// TODO Auto-generated method stub
				Logger.i(TAG, "onSuccess.object="+object.toString());
				if(mRefreshListView != null){
					mRefreshListView.onRefreshComplete();
				}
				if(object != null){
					MyloginVideoEntity entity = (MyloginVideoEntity)object;
					com.v1.video.domain.BaseEntity.Header header = entity.getHeader();
					if(header == null){
						ToastAlone.showToast(getActivity(), "未知错误", Toast.LENGTH_SHORT);
						if(!isDelete){
							mRefreshListView.setMode(Mode.PULL_FROM_START);
						}else{
							mRefreshListView.setMode(Mode.DISABLED);
						}
//						return;
					}else if(!header.getStatus().equals("1")){
						ToastAlone.showToast(getActivity(), header.getMessage(), Toast.LENGTH_SHORT);
						if(!isDelete){
							mRefreshListView.setMode(Mode.PULL_FROM_START);
						}else{
							mRefreshListView.setMode(Mode.DISABLED);
						}
//						return;
					}else if(header.getStatus().equals("1")){
						if(entity.getBody() != null){
							if(entity.getBody().getPage_num() != null && entity.getBody().getPage_num().length() > 0){
								page_num = Integer.parseInt(entity.getBody().getPage_num());
							}else{
								page_num = 1;
							}
							if(entity.getBody().getData() != null){
								if(curIndex == 0){
									mLstData.clear();
									mLstData.addAll(entity.getBody().getData());
								}else{
									mLstData.addAll(entity.getBody().getData());
								}
								mAdapter.setLstData(mLstData);
								if(curIndex < (page_num - 1)){
									if(!isDelete){
										mRefreshListView.setMode(Mode.BOTH);
									}
									isNoUpDown = false;
								}else{
									isNoUpDown = true;
									if(!isDelete){
										mRefreshListView.setMode(Mode.PULL_FROM_START);
									}
								}
//								if(mLstData != null){
//									mLstData.clear();
//									mLstData.addAll(entity.getBody().getData());
//								}else{
//									mLstData = entity.getBody().getData();
//								}
//								
//								if(mLstData.size() >= COUNT_GET_INFO){
//									mRefreshListView.setMode(Mode.BOTH);
//								}else{
//									isNoUpDown = true;
//									mRefreshListView.setMode(Mode.PULL_DOWN_TO_REFRESH);
//								}
//								if(curIndex == 0){
//									mAdapter.setLstData(mLstData);
//								}else{
//									mAdapter.setAddLstData(mLstData);
//								}
//								mAdapter.notifyDataSetChanged();
							}else{
								if(curIndex == 0){
									mListView.setEmptyView(mEmptyView);
								}
							}
							
						}else{
//							toast(header.getMessage());
						}
					}
				}
				
			}

			@Override
			public void onFailure(int code, String message) {
				// TODO Auto-generated method stub
				Logger.i(TAG, message);
				if(curIndex == 0){
					mListView.setEmptyView(mEmptyView);
				}
				if(mRefreshListView != null){
					mRefreshListView.onRefreshComplete();
				}
				if(!isDelete){
					mRefreshListView.setMode(Mode.PULL_FROM_START);
				}else{
					mRefreshListView.setMode(Mode.DISABLED);
				}
			}
		});
    }
	
	/***
     * 获取视频列表
     */
    private void getVideoList(){
    	String url = V1VideoHttpApi.GET_VIDEO_LIST_USER() + "&uid="+LoginInfo.getInstance().getUserId()+"&p="+curIndex+"&s="+COUNT_GET_INFO;
    	Logger.i(TAG, "视频列表Url ="+url);
		RequestManager.getInstance().getRequest(getActivity(), url, null, MyloginVideoEntity.class, 0, "MyLoginVideoFragment", new OnResponseListener(){

			@Override
			public void onSuccess(Object object, int code, String message,String key) {
				// TODO Auto-generated method stub
				Logger.i(TAG, "onSuccess.object="+object.toString());
				if(mRefreshListView != null){
					mRefreshListView.onRefreshComplete();
				}
				if(object != null){
					MyloginVideoEntity entity = (MyloginVideoEntity)object;
					com.v1.video.domain.BaseEntity.Header header = entity.getHeader();
					if(header == null){
						ToastAlone.showToast(getActivity(), "未知错误", Toast.LENGTH_SHORT);
						if(!isDelete){
							mRefreshListView.setMode(Mode.PULL_FROM_START);
						}else{
							mRefreshListView.setMode(Mode.DISABLED);
						}
//						return;
					}else if(!header.getStatus().equals("1")){
						ToastAlone.showToast(getActivity(), header.getMessage(), Toast.LENGTH_SHORT);
						if(!isDelete){
							mRefreshListView.setMode(Mode.PULL_FROM_START);
						}else{
							mRefreshListView.setMode(Mode.DISABLED);
						}
//						return;
					}else if(header.getStatus().equals("1")){
						if(entity.getBody() != null){
							if(entity.getBody().getPage_num() != null && entity.getBody().getPage_num().length() > 0){
								page_num = Integer.parseInt(entity.getBody().getPage_num());
							}else{
								page_num = 1;
							}
							if(entity.getBody().getData() != null){
								if(curIndex == 0){
									mLstData.clear();
									mLstData.addAll(entity.getBody().getData());
								}else{
									mLstData.addAll(entity.getBody().getData());
								}
								mAdapter.setLstData(mLstData);
								if(curIndex < (page_num - 1)){
									if(!isDelete){
										mRefreshListView.setMode(Mode.BOTH);
									}
									isNoUpDown = false;
								}else{
									isNoUpDown = true;
									if(!isDelete){
										mRefreshListView.setMode(Mode.PULL_FROM_START);
									}
									
								}
							}else{
								if(curIndex == 0){
									mListView.setEmptyView(mEmptyView);
								}
							}
							
						}else{
//							toast(header.getMessage());
						}
					}
				}
				
			}

			@Override
			public void onFailure(int code, String message) {
				// TODO Auto-generated method stub
				Logger.i(TAG, message);
				if(curIndex == 0){
					mListView.setEmptyView(mEmptyView);
				}
				if(mRefreshListView != null){
					mRefreshListView.onRefreshComplete();
				}
				if(!isDelete){
					mRefreshListView.setMode(Mode.PULL_FROM_START);
				}else{
					mRefreshListView.setMode(Mode.DISABLED);
				}
			}
		});
    }

	private Handler handler = new Handler(){

		@Override
		public void handleMessage(Message msg) {
			// TODO Auto-generated method stub
			super.handleMessage(msg);
			switch(msg.what){
			case 0:
				if(mRefreshListView != null){
					mRefreshListView.onRefreshComplete();
				}
				break;
			}
		}
		
	};
	
	public ArrayList<VideoInfo4> getTheSelectVideo(){
		if(mAdapter != null){
			return mAdapter.getTheSelectVideo();
		}else{
			return null;
		}
	}
	
	@Override
	public void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		MobclickAgent.onPageStart("MyLoginVideoFragment");
	}

	@Override
	public void onPause() {
		// TODO Auto-generated method stub
		super.onPause();
		MobclickAgent.onPageEnd("MyLoginVideoFragment");
	}

	/**
	 * 刷新数据
	 */
	public void refresh() {
//		if (!TextUtils.isEmpty(mUserId)) {
//			mCurPage = 0;
//			new GetVideoInfoTask().execute();
//		}
		if (mRefreshListView != null) {
			mRefreshListView.doPullRefreshing(100);
		}
	}

	/**
	 * 加载更多
	 */
	public void loadMore() {
//		if (!TextUtils.isEmpty(mUserId)) {
//			new GetVideoInfoTask().execute();
//		}
	}

	@Override
	public void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
//		if (mCasdialog != null) {
//			if (mCasdialog.isShowing()) {
//				mCasdialog.dismiss();
//			}
//			mCasdialog = null;
//		}
		
		if (mAdapter != null) {
			mAdapter = null;
		}
	}
	
}
